<!--
 * @Author: dongxueting
 * @Date: 2023-05-12 14:21:15
 * @LastEditTime: 2023-10-11 16:31:47
 * @email: dong_xt@reachauto.com
 * @Description: 
-->
<template>
	<el-dialog
		title="Import Layout Config"
		width="500px"
		:visible.sync="dialogVisible"
		@open="dialogOpen"
	>
		<div style="width: 360px;margin: 0 auto">
			<el-upload
				class="upload-demo"
				:file-list="fileList"
				drag
				:limit="1"
				:action="''"
				accept=".json"
				:http-request="httpRequest"
			>
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">Drag and drop files here，or <em>click to upload</em></div>
				<div class="el-upload__tip" slot="tip">only accept .json files</div>
			</el-upload>
		</div>
		<div slot="footer" class="dialog-footer">
			<el-button @click="dialogVisible = false">Cancel</el-button>
			<el-button type="primary" @click="confirm">Confirm to Import</el-button>
		</div>
	</el-dialog>
</template>

<script>
export default {
	name: 'ConfigDialog',
	props: {
		visible: {
			type: Boolean,
			default: false
		}
	},
	computed: {
		dialogVisible: {
			get() {
				return this.visible;
			},
			set(val) {
				this.$emit("update:visible", val);
			}
		}
	},
	data() {
		return {
			fileList: [],
			json: null
		}
	},
	methods: {
		dialogOpen() {
			this.fileList = []
			this.json = null
		},
		httpRequest(a) {
			const { file } = a
			const reader = new FileReader()
			reader.readAsText(file)
			reader.onload = e => {
				if(e.target && e.target.result) {
					const json = JSON.parse(e.target.result.toString())
					if (Object.keys(json).includes("layout")) {
						this.json = json
					} else {
						this.$message.error("invalid layout json")
					}
					if(Object.keys(json).includes("bottomConfig")){
						this.json = json
					} else {
						this.$message.error("invalid bottomConfig json")
					}
				}
			}
		},
		confirm() {
			this.$emit("import", this.json)
			this.dialogVisible = false
		}
	}
}
</script>

<style scoped lang="scss">
.upload-demo{
	width: 360px;
}
</style>
